package com.zhentao.studyim.controller;

import com.zhentao.studyim.dto.ApiResponse;
import com.zhentao.studyim.dto.FriendRequestDto;
import com.zhentao.studyim.entity.FriendRequest;
import com.zhentao.studyim.entity.User;
import com.zhentao.studyim.service.FriendService;
import com.zhentao.studyim.util.JwtUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 好友相关控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/friend")
@RequiredArgsConstructor
public class FriendController {

    private final FriendService friendService;
    private final JwtUtil jwtUtil;

    /**
     * 搜索用户
     * @param keyword 搜索关键词
     * @param token JWT令牌
     * @return 用户列表
     */
    @GetMapping("/search")
    public ApiResponse<List<User>> searchUsers(@RequestParam String keyword,
                                               @RequestHeader("Authorization") String token) {
        try {
            // 从token中获取当前用户ID
            String actualToken = token.replace("Bearer ", "");
            Long currentUserId = jwtUtil.getUserIdFromToken(actualToken);
            
            log.info("搜索用户: keyword={}, currentUserId={}", keyword, currentUserId);
            
            List<User> users = friendService.searchUsers(keyword, currentUserId);
            return ApiResponse.success(users);
        } catch (Exception e) {
            log.error("搜索用户失败", e);
            return ApiResponse.error("搜索失败: " + e.getMessage());
        }
    }

    /**
     * 发送好友申请
     * @param requestBody 申请信息
     * @param token JWT令牌
     * @return 申请结果
     */
    @PostMapping("/request")
    public ApiResponse<String> sendFriendRequest(@RequestBody Map<String, Object> requestBody,
                                                 @RequestHeader("Authorization") String token) {
        try {
            // 从token中获取当前用户ID
            String actualToken = token.replace("Bearer ", "");
            Long fromUserId = jwtUtil.getUserIdFromToken(actualToken);
            
            Long toUserId = Long.valueOf(requestBody.get("toUserId").toString());
            String message = (String) requestBody.get("message");
            
            log.info("发送好友申请: fromUserId={}, toUserId={}, message={}", fromUserId, toUserId, message);
            
            String result = friendService.sendFriendRequest(fromUserId, toUserId, message);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("发送好友申请失败", e);
            return ApiResponse.error("发送申请失败: " + e.getMessage());
        }
    }

    /**
     * 获取收到的好友申请列表
     * @param token JWT令牌
     * @return 好友申请列表
     */
    @GetMapping("/requests/received")
    public ApiResponse<List<FriendRequestDto>> getReceivedFriendRequests(@RequestHeader("Authorization") String token) {
        try {
            // 从token中获取当前用户ID
            String actualToken = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(actualToken);
            
            log.info("获取收到的好友申请: userId={}", userId);
            
            List<FriendRequestDto> requests = friendService.getReceivedFriendRequestDtos(userId);
            return ApiResponse.success(requests);
        } catch (Exception e) {
            log.error("获取好友申请失败", e);
            return ApiResponse.error("获取申请失败: " + e.getMessage());
        }
    }

    /**
     * 获取发出的好友申请列表
     * @param token JWT令牌
     * @return 好友申请列表
     */
    @GetMapping("/requests/sent")
    public ApiResponse<List<FriendRequestDto>> getSentFriendRequests(@RequestHeader("Authorization") String token) {
        try {
            // 从token中获取当前用户ID
            String actualToken = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(actualToken);
            
            log.info("获取发出的好友申请: userId={}", userId);
            
            List<FriendRequestDto> requests = friendService.getSentFriendRequestDtos(userId);
            return ApiResponse.success(requests);
        } catch (Exception e) {
            log.error("获取好友申请失败", e);
            return ApiResponse.error("获取申请失败: " + e.getMessage());
        }
    }

    /**
     * 同意好友申请
     * @param requestId 申请ID
     * @param token JWT令牌
     * @return 处理结果
     */
    @PostMapping("/requests/{requestId}/accept")
    public ApiResponse<String> acceptFriendRequest(@PathVariable Long requestId,
                                                   @RequestHeader("Authorization") String token) {
        try {
            // 从token中获取当前用户ID
            String actualToken = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(actualToken);
            
            log.info("同意好友申请: requestId={}, userId={}", requestId, userId);
            
            String result = friendService.acceptFriendRequest(requestId, userId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("同意好友申请失败", e);
            return ApiResponse.error("处理申请失败: " + e.getMessage());
        }
    }

    /**
     * 拒绝好友申请
     * @param requestId 申请ID
     * @param token JWT令牌
     * @return 处理结果
     */
    @PostMapping("/requests/{requestId}/reject")
    public ApiResponse<String> rejectFriendRequest(@PathVariable Long requestId,
                                                   @RequestHeader("Authorization") String token) {
        try {
            // 从token中获取当前用户ID
            String actualToken = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(actualToken);
            
            log.info("拒绝好友申请: requestId={}, userId={}", requestId, userId);
            
            String result = friendService.rejectFriendRequest(requestId, userId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("拒绝好友申请失败", e);
            return ApiResponse.error("处理申请失败: " + e.getMessage());
        }
    }

    /**
     * 获取好友列表
     * @param token JWT令牌
     * @return 好友列表
     */
    @GetMapping("/list")
    public ApiResponse<List<User>> getFriendList(@RequestHeader("Authorization") String token) {
        try {
            // 从token中获取当前用户ID
            String actualToken = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(actualToken);
            
            log.info("获取好友列表: userId={}", userId);
            
            List<User> friends = friendService.getFriendList(userId);
            return ApiResponse.success(friends);
        } catch (Exception e) {
            log.error("获取好友列表失败", e);
            return ApiResponse.error("获取好友列表失败: " + e.getMessage());
        }
    }

    /**
     * 删除好友
     * @param friendId 好友ID
     * @param token JWT令牌
     * @return 删除结果
     */
    @DeleteMapping("/{friendId}")
    public ApiResponse<String> deleteFriend(@PathVariable Long friendId,
                                            @RequestHeader("Authorization") String token) {
        try {
            // 从token中获取当前用户ID
            String actualToken = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(actualToken);
            
            log.info("删除好友: userId={}, friendId={}", userId, friendId);
            
            String result = friendService.deleteFriend(userId, friendId);
            return ApiResponse.success(result);
        } catch (Exception e) {
            log.error("删除好友失败", e);
            return ApiResponse.error("删除好友失败: " + e.getMessage());
        }
    }

    /**
     * 检查是否是好友
     * @param friendId 好友ID
     * @param token JWT令牌
     * @return 是否是好友
     */
    @GetMapping("/check/{friendId}")
    public ApiResponse<Boolean> isFriend(@PathVariable Long friendId,
                                         @RequestHeader("Authorization") String token) {
        try {
            // 从token中获取当前用户ID
            String actualToken = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(actualToken);
            
            log.info("检查是否是好友: userId={}, friendId={}", userId, friendId);
            
            boolean isFriend = friendService.isFriend(userId, friendId);
            return ApiResponse.success(isFriend);
        } catch (Exception e) {
            log.error("检查好友关系失败", e);
            return ApiResponse.error("检查失败: " + e.getMessage());
        }
    }

    /**
     * 获取待处理的好友申请数量
     * @param token JWT令牌
     * @return 申请数量
     */
    @GetMapping("/requests/count")
    public ApiResponse<Long> getPendingRequestCount(@RequestHeader("Authorization") String token) {
        try {
            // 从token中获取当前用户ID
            String actualToken = token.replace("Bearer ", "");
            Long userId = jwtUtil.getUserIdFromToken(actualToken);
            
            log.info("获取待处理申请数量: userId={}", userId);
            
            long count = friendService.getPendingRequestCount(userId);
            return ApiResponse.success(count);
        } catch (Exception e) {
            log.error("获取申请数量失败", e);
            return ApiResponse.error("获取数量失败: " + e.getMessage());
        }
    }
}
